package com.czh.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.czh.domain.AuthCodeDO;
import com.czh.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.ThreadLocalRandom;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private AuthCodeService authCodeService;

    @GetMapping("/validate/{email}/{code}")
    public int validate(@PathVariable String email, @PathVariable String code) {
        AuthCodeDO authCodeDO = authCodeService.getOne(Wrappers.<AuthCodeDO>lambdaQuery()
                .eq(AuthCodeDO::getEmail, email)
                .orderByDesc(AuthCodeDO::getId)
                .last("limit 1"));
        if (authCodeDO == null || authCodeDO.getExpireTime().isBefore(LocalDateTime.now())) {
            return 2;
        }
        if (!authCodeDO.getCode().equals(code)) {
            return 1;
        }
        return 0;
    }

    @GetMapping("/create/{email}")
    public boolean create(@PathVariable String email) {
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        AuthCodeDO authCodeDO = new AuthCodeDO();
        LocalDateTime now = LocalDateTime.now();
        authCodeDO.setCreateTime(now);
        authCodeDO.setExpireTime(now.plus(10, ChronoUnit.MINUTES));
        authCodeDO.setEmail(email);
        authCodeDO.setCode(String.format("%06d", threadLocalRandom.nextInt(1000000)));
        return authCodeService.save(authCodeDO);
    }
}
